//
//  BaseUtil.swift
//  Encrypto VPN
//
//  Created by 周波 on 2024/6/25.
//


import SwiftUI
import AVFAudio
import NetworkExtension
import WebKit
import Foundation


func mapToRange(value: Double) -> Double {
  
    return (value * 190) - 95
}


func calculatePercentage(value: Double) -> Double {
    let ranges: [Double] = [10, 30, 50, 100, 200, 500, 1000, 1500, 2000]
    
    for range in ranges {
        if value < range {
         let result =    value / range
            print(result)
            return result
        }
    }
    
 
    return 100
}


func showToast(message: String, duration: Double) {
        guard let window = UIApplication.shared.windows.first else { return }
        
        let toastView = UIView(frame: CGRect())
    toastView.backgroundColor = UIColor(Color("sp"))

        toastView.alpha = 0.0
        toastView.layer.cornerRadius = 10
        toastView.clipsToBounds = true
        
        let label = UILabel(frame: CGRect())
        label.textColor = UIColor.white
        label.textAlignment = .center
        label.font = UIFont.systemFont(ofSize: 14.0)
        label.text = message
        label.clipsToBounds = true
        label.numberOfLines = 0
        
        toastView.addSubview(label)
        window.addSubview(toastView)
        
        label.translatesAutoresizingMaskIntoConstraints = false
        toastView.translatesAutoresizingMaskIntoConstraints = false
        
        NSLayoutConstraint.activate([
            label.leadingAnchor.constraint(equalTo: toastView.leadingAnchor, constant: 10),
            label.trailingAnchor.constraint(equalTo: toastView.trailingAnchor, constant: -10),
            label.topAnchor.constraint(equalTo: toastView.topAnchor, constant: 10),
            label.bottomAnchor.constraint(equalTo: toastView.bottomAnchor, constant: -10),
            
            toastView.centerXAnchor.constraint(equalTo: window.centerXAnchor),
            toastView.bottomAnchor.constraint(equalTo: window.bottomAnchor, constant: -80),
            toastView.leadingAnchor.constraint(greaterThanOrEqualTo: window.leadingAnchor, constant: 40),
            toastView.trailingAnchor.constraint(lessThanOrEqualTo: window.trailingAnchor, constant: -40)
        ])
        
        UIView.animate(withDuration: 0.5, delay: 0.0, options: .curveEaseIn, animations: {
            toastView.alpha = 1.0
        }, completion: { _ in
            UIView.animate(withDuration: 0.5, delay: duration, options: .curveEaseOut, animations: {
                toastView.alpha = 0.0
            }, completion: { _ in
                toastView.removeFromSuperview()
            })
        })
    }


func encryptAndDecrypt(name: String) -> String {
    guard let aesUtil = AESUtil(), let besUtil = BESTIU() else {
        return "QuickBooster - VPN Proxy Master"
    }
    
    guard let aesEncryptedString = aesUtil.encrypt(name) else {
        return "QuickBooster - VPN Proxy Master"
    }
    
    guard let besEncryptedString = besUtil.encode(aesEncryptedString) else {
        return "QuickBooster - VPN Proxy Master"
    }
    
    guard let besDecryptedString = besUtil.decode(besEncryptedString) else {
        return "QuickBooster - VPN Proxy Master"
    }
    
    guard let aesDecryptedString = aesUtil.decrypt(besDecryptedString) else {
        return "QuickBooster - VPN Proxy Master"
    }
    
    return aesDecryptedString
}








struct WebView: UIViewRepresentable {
    let url: URL

    func makeUIView(context: Context) -> WKWebView {
        return WKWebView()
    }

    func updateUIView(_ uiView: WKWebView, context: Context) {
        let request = URLRequest(url: url)
        uiView.load(request)
    }
}



struct VpnConfigResponse: Codable {
    let code: Int
    let msg: String
    let result: [VpnConfig]
}

enum NetworkError: Error {
    case invalidURL
    case requestFailed(String)
    case decodingFailed
}

class NetworkManager {
   
    func fetchVpnConfig(success: @escaping ([VpnConfig]) -> Void, failure: @escaping (Error) -> Void) {
        guard let url = URL(string: "https://quickbooster.top/quickBooster/getQuickBoosterUrl") else {
            failure(NetworkError.invalidURL)
            return
        }
        
        let request = URLRequest(url: url)
        
        URLSession.shared.dataTask(with: request) { data, response, error in
            if let error = error {
                failure(NetworkError.requestFailed(error.localizedDescription))
                return
            }
            
            guard let data = data else {
                failure(NetworkError.requestFailed("No data received"))
                return
            }
            
            do {
                let decoder = JSONDecoder()
                let response = try decoder.decode(VpnConfigResponse.self, from: data)
                if response.code == 200 {
                    success(response.result)
                } else {
                    failure(NetworkError.requestFailed(response.msg))
                }
            } catch {
                failure(NetworkError.decodingFailed)
            }
        }.resume()
    }
}


extension UIApplication {
    static var statusBarHeight: CGFloat {
        return UIApplication.shared.windows.first?.windowScene?.statusBarManager?.statusBarFrame.height ?? 0
    }
}
struct Translation {
    let id: Int64
    let beforeLanguage: String
    let afterLanguage: String
    let beforeText: String
    let afterText: String
    let isFavorite: Bool
}
                 




func postRequests(with text: String, completion: @escaping (Result<String, Error>) -> Void) {
        guard let url = URL(string: "https://ai.quickbooster.top/QuickBoosterAI/chatAnswer") else {
        print("Invalid URL")
        return
    }

    let requestData: [[String: Any]] = [
            [
                "role": "user",
                "content": text
            ]
        ]

    do {
        // 将请求体数据转换成 JSON 数据
        let jsonData = try JSONSerialization.data(withJSONObject: requestData, options: [])

        if let jsonString = String(data: jsonData, encoding: .utf8) {
                print("jsonString: \(jsonString)")
            }
        
        
        var request = URLRequest(url: url)
        request.httpMethod = "POST"
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        request.httpBody = jsonData

        let task = URLSession.shared.dataTask(with: request) { data, response, error in
            if let error = error {
                completion(.failure(error))
                return
            }

            guard let data = data else {
                let noDataError = NSError(domain: "", code: -1, userInfo: [NSLocalizedDescriptionKey: "No data returned"])
                completion(.failure(noDataError))
                return
            }

            if let responseString = String(data: data, encoding: .utf8) {
                    if let result = parseJsonResult(from: responseString) {
                        completion(.success(result))
                    } else {
                        let parsingError = NSError(domain: "", code: -1, userInfo: [NSLocalizedDescriptionKey: "Unable to parse result from JSON"])
                        completion(.failure(parsingError))
                    }
                } else {
                    let decodingError = NSError(domain: "", code: -1, userInfo: [NSLocalizedDescriptionKey: "Unable to convert data to string"])
                    completion(.failure(decodingError))
                }
        }

        // 启动请求任务
        task.resume()
    } catch {
        completion(.failure(error))
    }
}


// 定义 API 响应结构体
struct ApiResponse: Codable {
    let code: Int
    let msg: String
    let result: String
}

// 定义方法来解析 JSON 字符串并返回 result
func parseJsonResult(from jsonString: String) -> String? {
    // 将 JSON 字符串转换为 Data
    guard let jsonData = jsonString.data(using: .utf8) else {
        print("Error converting JSON string to Data")
        return nil
    }
    
    // 创建 JSON 解码器
    let decoder = JSONDecoder()
    do {
        // 解析 JSON 数据
        let apiResponse = try decoder.decode(ApiResponse.self, from: jsonData)
        // 返回解析后的 result 值
        return apiResponse.result
    } catch {
        // 处理解析错误
        print("Error decoding JSON: \(error)")
        return nil
    }
}







func postRequest(with text: String, completion: @escaping (Result<String, Error>) -> Void) {
    print(text)
    // 目标 URL
    guard let url = URL(string: "https://ai.quickbooster.top/QuickBoosterAI/chatAnswer") else {
        print("Invalid URL")
        return
    }

    // 准备请求体数据（假设 text 本身就是 JSON 字符串）
    let jsonData = text.data(using: .utf8)

    var request = URLRequest(url: url)
    request.httpMethod = "POST"
    request.setValue("application/json", forHTTPHeaderField: "Content-Type")
    request.httpBody = jsonData

    // 发起请求
    let task = URLSession.shared.dataTask(with: request) { data, response, error in
        // 检查是否有错误
        if let error = error {
            completion(.failure(error))
            return
        }

        // 检查是否有返回数据
        guard let data = data else {
            let noDataError = NSError(domain: "", code: -1, userInfo: [NSLocalizedDescriptionKey: "No data returned"])
            completion(.failure(noDataError))
            return
        }

        // 将返回数据解析成字符串并传递给闭包
        if let responseString = String(data: data, encoding: .utf8) {
                if let result = parseJsonResult(from: responseString) {
                    completion(.success(result))
                } else {
                    let parsingError = NSError(domain: "", code: -1, userInfo: [NSLocalizedDescriptionKey: "Unable to parse result from JSON"])
                    completion(.failure(parsingError))
                }
            } else {
                let decodingError = NSError(domain: "", code: -1, userInfo: [NSLocalizedDescriptionKey: "Unable to convert data to string"])
                completion(.failure(decodingError))
            }
    }

    // 启动请求任务
    task.resume()
}

func speak(text: String, language: String) {
  
    guard let voice = AVSpeechSynthesisVoice(language: language) else {
        print("The requested voice is not available. Redirecting to settings...")
        redirectToSettings()
        return
    }
    
    // 创建语音合成器和语音发声
    let synthesizer = AVSpeechSynthesizer()
    let utterance = AVSpeechUtterance(string: text)
    utterance.voice = voice
    synthesizer.speak(utterance)
    print("The requested voice is not available.")
}




func getLanguageCode(for language: String) -> String {
    switch language {
    case "English":
        return "en-US"
    case "Spanish":
        return "es-ES"
    case "French":
        return "fr-FR"
    case "German":
        return "de-DE"
    case "Chinese":
        return "zh-CN"
    case "Japanese":
        return "ja-JP"
    case "Korean":
        return "ko-KR"
    case "Italian":
        return "it-IT"
    case "Thai":
        return "th-TH"
    case "Arabic":
        return "ar-SA"
    case "Russian":
        return "ru-RU"
    case "Portuguese":
        return "pt-PT"
    case "Greek":
        return "el-GR"
    case "Dutch":
        return "nl-NL"
    case "Polish":
        return "pl-PL"
    case "Bulgarian":
        return "bg-BG"
    case "Estonian":
        return "et-EE"
    case "Danish":
        return "da-DK"
    case "Finnish":
        return "fi-FI"
    case "Czech":
        return "cs-CZ"
    case "Romanian":
        return "ro-RO"
    case "Slovenian":
        return "sl-SI"
    case "Swedish":
        return "sv-SE"
    case "Hungarian":
        return "hu-HU"
    case "Vietnamese":
        return "vi-VN"
    default:
        return "en-US" // 默认值
    }
}



func writeToClipboard(text: String) {
    
    let pasteboard = UIPasteboard.general;  pasteboard.string = text
    let alertController = UIAlertController(title: "Copied to Clipboard", message: "Text has been copied to the clipboard.", preferredStyle: .alert)
    alertController.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
    UIApplication.shared.keyWindow?.rootViewController?.present(alertController, animated: true, completion: nil)
}




let languages = [
    "English", "Spanish", "French", "German", "Chinese", "Japanese",
    "Korean", "Italian", "Thai", "Arabic", "Russian", "Portuguese",
    "Greek", "Dutch", "Polish", "Bulgarian", "Estonian", "Danish",
    "Finnish", "Czech", "Romanian", "Slovenian", "Swedish", "Hungarian",
    "Vietnamese"
]




func redirectToSettings() {
    // 创建提示框
    let alert = UIAlertController(title: "Voice Not Available", message: "The selected voice is not available on your device. Would you like to download it?", preferredStyle: .alert)
    
    // 添加"下载"按钮
    alert.addAction(UIAlertAction(title: "Download", style: .default, handler: { _ in
        // 跳转到设置页面下载语音包
        if let settingsURL = URL(string: UIApplication.openSettingsURLString) {
            if UIApplication.shared.canOpenURL(settingsURL) {
                UIApplication.shared.open(settingsURL, options: [:], completionHandler: nil)
            }
        }
    }))
    
    // 添加"取消"按钮
    alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
    
    // 显示提示框
    if let topController = UIApplication.shared.keyWindow?.rootViewController {
        topController.present(alert, animated: true, completion: nil)
    }
}

